package com.seley.service.login;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
	
	@Autowired
	private TokenMgr tokenMgr;

	@PostMapping("/getToken")
	public Map<String,Object> getToken(@RequestParam("username") String username, @RequestParam("password") String password) {
		Map<String,Object> rs = new HashMap<String, Object>();
		
		if ("admin".equals(username) && "admin".equals(password)) {
			rs.put("success", true);
			rs.put("username", username);
			rs.put("token", tokenMgr.createJWT(username));
		} else {
			rs.put("success", false);
			rs.put("username", username);
		}
		
		return rs;
	}
	
	@PostMapping("/checkToken")
	public boolean validateJWT(@RequestParam("token") String token) {
		return tokenMgr.validateJWT(token);
	}
	
	@PostMapping("/reflashToken")
	public String reflashToken(@RequestParam("username") String username, @RequestParam("token") String token) {
		if(tokenMgr.validateJWT(token)) {
			return tokenMgr.createJWT(username);
		}
		
		return null;
	}
	
}
